package fxsjdcxt;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.rowset.CachedRowSet;

import com.sun.rowset.CachedRowSetImpl;

public class AccessDBManager {
	private static final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
	private static final String URL = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s";
	private static final String USERNAME = "";
	private static final String PASSWORD = "";
	private static String url;

	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static Connection getConnection() {
		try {
			InputStreamReader in = new InputStreamReader(new FileInputStream("db.ini"), "UTF-8");
			Properties prop = new Properties();
			prop.load(in);
			in.close();
			url = String.format(URL, prop.getProperty("path"));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		try {
			Connection conn = DriverManager.getConnection(url, USERNAME, PASSWORD);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void closeConnection(Connection conn) {
		try {
			if (null != conn && !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static CachedRowSet query(Connection conn, String sql) {
		try {
			CachedRowSet crs = new CachedRowSetImpl();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			crs.populate(rs);
			rs.close();
			stmt.close();
			return crs;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}